/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package no.ffi.tpm.utils;

import java.io.FileOutputStream;
import java.security.PublicKey;
import java.security.interfaces.RSAPublicKey;
import javax.trustedcomputing.tpm.TPMContext;
import no.ffi.tpm.TPMClient;
import no.ffi.tpm.TPMiSRequest;

import no.ffi.tpm.crypto.*;


/**
 * This class contains a simulation of the process used to certify a
 * key with a TPM and get a certificate for it from an IdP.
 * 
 * @author fma 
 */
public class LegacyKeyCertificationTest {

    /*
     * This method creates an AIK, and then a Legacy, which is in turn certified with the AIK.
     * The information is then sent to an IdP to verify the certification and generate a certificate for the key.
     */
    public static void main(String[] args) throws Exception {
        TPMContext context=TPMContext.getInstance();
        context.connect(null);
        context.getTPMInstance().extendPCR(0, context.getDigest(context.getTPMInstance().getRandom(20)));
        TPMClient client=new TPMClient("","");
        System.out.println("wee: " + client);
        client.getIdS("legacyPass");
        
        /*CryptoOperations crypto= CryptoOperationsFactory.getInstance(CryptoOperationsFactory.TPM,"Federico");
        TPMiSRequest req=(TPMiSRequest) crypto.getISrequest();
        byte[] ser=crypto.serialize(req);
        FileOutputStream fo;
            
        try {
            //Store the uuid of the AIK used in the request in the file name
            fo = new FileOutputStream("LKRequest.file");
            fo.write(ser);
	    fo.close();
        } catch(Exception ex) {
            
        }
        
        PublicKey aik=((TPMCryptoOperations)crypto).getAIK();
        System.out.println(" aik modulus="+ ((RSAPublicKey) aik).getModulus());
        PublicKey userKey=((TPMCryptoOperations)crypto).getUserPubKey();
        boolean valid=req.verifyRequest(aik,userKey, new byte[20]);
        if (valid) {
                        System.out.println("The key is valid, here is your Identity statement....");
                    }
        /*ValidationData val=crypto.certifyKey("Federico's_key");
        /*
         * This data structure contains three fields:
         * The information in clear about the key to certify, which is what is signed by the AIK.
         * It contains:
         * - the SHA-1 of the key modulus
         * - The nonce used to guarantee freshness (right now simply a new byte[20])
         * - lots of other things
         */
        /*byte[] plainData = val.getData();
        //The nonce, which must be equal to the one in plainData
        byte[] nonce = val.getNonce();
        //The signature itself
        byte[] signature = val.getValidationData();
        
        //Let's pretend we serialized and sent the certificateRequest to the IdP
        //On the IdP we deserialize the certificateRequest and decode the TPM_CERTIFY_INFO struct
        DecodeTPMCertInfo tpmInfo=new DecodeTPMCertInfo(plainData);
        //Create a certificate request with this information and send it to IdP
        LegacyKeyCertifyInfo certificateRequest = new LegacyKeyCertifyInfo(plainData,crypto.getPubKey(), crypto.getAIK(), signature,crypto.getMyDistinguishedName(),tpmInfo.getKeyDigIndex(),tpmInfo.getNonceIndex());
        
   
        //Calculate the key digest separately based on the modulus sent in the CertificateRequest
        byte[] calculatedDig = CryptoOperations.pubKeytoSHA1(certificateRequest.getCertifiedKey());

        //Check that the public key digests match
        if (Arrays.equals(certificateRequest.getCertifiedKeySHA1(), calculatedDig)) {
            //Then the nonces match
            if (Arrays.equals(certificateRequest.getNonce(), nonce)) {
                try {
                    //Then check the signature by using the AIK certificate 
                    //that should actually be preloaded on the IdP
                    PublicKey aik = certificateRequest.certifyingKey;              
                    //Get the signature sent by the client
                    //byte[] sign = certificateRequest.getSignature();
                    //verify signature
                    //Signature sig = Signature.getInstance("SHA1withRSA");
                   // sig.initVerify(aik);
                    //sig.update(plainData);
                    boolean valid = CryptoOperations.verify(certificateRequest, aik);//sig.verify(sign);
                    if (valid) {
                        System.out.println("The key is valid, here is your Identity statement....");
                    }
                } catch (Exception ex) {
                    Logger.getLogger(LegacyKeyCertificationTest.class.getName()).log(Level.SEVERE, null, ex);
                } 
            } else {
                System.out.println("Nonces are not equal");
            }
        } else {
            System.out.println("PubKey digests are not equal");
        }*/
    }
}
